package com.sina.shop.manage.dao.goods;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.Status;
import com.sina.shop.domain.goods.Goods;
import com.sina.shop.domain.goods.Goods_;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2018-01-11-14:24
 */
@Repository("goodsManageDao")
public class GoodsManageDaoImpl extends ShopDataSourceDao implements GoodsManageDao {


    @Override
    public int deleteGoods(Long id) {
        /*String hql = "delete from Goods g where g.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });*/
        String hql = "update Goods g set g.status = :status where g.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("status", Status.NOT_USE);
            return query.executeUpdate();
        });
    }

    @Override
    public List<Map<String, Object>> getGoodsIdAndName() {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Goods> root = criteriaQuery.from(Goods.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    root.get(Goods_.id).as(Long.class).alias("id"),
                    root.get(Goods_.name).alias("name")
            );

            criteriaQuery.orderBy(
                    builder.asc(root.get(Goods_.id))
            );
            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);

            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }


    @Override
    public List<Map<String, Object>> getGoodsList(Goods goods) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Goods> root = criteriaQuery.from(Goods.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    goodsSelection(root)
            );

            Predicate predicate = goodsPredicate(goods, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Goods_.menu)),
                    builder.asc(root.get(Goods_.business)),
                    builder.asc(root.get(Goods_.id))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (goods.getPage() - 1) * goods.getRows();

            query.setFirstResult(first);
            query.setMaxResults(goods.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getGoodsCount(Goods goods) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Goods> root = criteriaQuery.from(Goods.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Goods_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    goodsPredicate(goods, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param goods
     * @param builder
     * @param root
     * @return
     */
    protected Predicate goodsPredicate(Goods goods, CriteriaBuilder builder
            , Root<Goods> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (goods.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Goods_.id), goods.getLastId())
            );
        }

        if (goods.getBusiness() != null) {
            list.add(
                    builder.equal(root.get(Goods_.business), goods.getBusiness().getId())
            );
        }

        if (goods.getMenu() != null) {
            list.add(
                    builder.equal(root.get(Goods_.menu), goods.getMenu().getId())
            );
        }

        if (goods.getName() != null) {
            list.add(
                    builder.equal(root.get(Goods_.name), goods.getName())
            );
        }


        list.add(
                builder.equal(root.get(Goods_.status), Status.USE)
        );

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> goodsSelection(Root<Goods> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Goods_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Goods_.business).alias("business"));
        list.add(root.get(Goods_.menu).alias("menu"));
        list.add(root.get(Goods_.name).alias("name"));
        list.add(root.get(Goods_.realPrice).alias("realPrice"));

        list.add(root.get(Goods_.price).alias("price"));
        list.add(root.get(Goods_.sum).alias("sum"));
        list.add(root.get(Goods_.description).alias("description"));
        list.add(root.get(Goods_.credit).alias("credit"));
        list.add(root.get(Goods_.isGroom).alias("isGroom"));

        list.add(root.get(Goods_.status).alias("status"));
        return list;
    }

    @Override
    public List<Goods> getGoodsByAdminAccount(String account) {
        String hql = "from Goods g where g.business.admin.account=:account";
        return list(hql, new String[]{"account"}, new Object[]{account}, -1, -1);
    }

    @Override
    public List<Goods> getGoodsList() {
        String hql = "select new Goods (id,name) from Goods";
        return list(hql, null, null, -1, -1);
    }
}
